import urllib2
import urllib
import base64
from twitrazzi.lib.xmlobject import XMLFile
import sys

class ApiBase():
    '''
    register urls 
    '''
    def __init__(self):
        self.debug = True
        self.user_agent_header = "NinjaCipher Python ApiBase"
    
    '''
    loop over dict and build query string
    '''
    def build_query(self,params):
        encoded_params = urllib.urlencode(params)
        query_string = ""
        for param in encoded_params:
            query_string = "%s&%s" % (query_string,param)
    
    '''
    submit a get request
    '''
    def submit_get(self,url,protected=False):
        if self.debug:
                sys.stderr.write(url)
                sys.stderr.flush()
                
        request = urllib2.Request(url)
        return self.send_request(request)
    
    '''
    submit a post request
    '''
    def submit_post(self,url,params,protected=False):
        if self.debug:
                sys.stderr.write(url)
                sys.stderr.flush()
        
        data = urllib.urlencode(params)
        request = urllib2.Request(url,data)
        return self.send_request(request)
    
    '''
    set the headers, send the request and pass along the response
    '''
    def send_request(self,request):
        request.add_header("User-agent", self.user_agent_header)
        try:
            handle = urllib2.urlopen(request)
            return True, handle.read()
        except IOError, e:
            return False, e.code
    
    '''
    if successfull build object from xml
    '''
    def handle_response(self, api_response):
        success, response = api_response
        if(success):
            response_doc = XMLFile(raw=response)
            if self.debug:
                sys.stderr.write(response_doc.toxml())
                sys.stderr.flush()
                
            return success, response_doc.root
        else:
            return success, response